<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';
import { Minus } from '@vben/icons';

import { ElButton, ElMessage } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { delLog, listLog } from '#/api/system/syslog/login';
import { $t } from '#/locales';
import { addDateRange } from '#/utils/common';

import { columnsSchema, querySchema } from './data';

const formOptions: VbenFormProps = {
  collapsed: true, // 默认展开
  schema: querySchema(), // 查询参数
  showCollapseButton: false, // 控制表单是否显示折叠按钮
  submitOnEnter: false, // 按下回车时是否提交表单
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridEvents: {},
  gridOptions: {
    checkboxConfig: {
      highlight: true,
      labelField: 'name',
    },
    columns: columnsSchema(),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (formValues.dateRange) {
            addDateRange(formValues, formValues.dateRange);
            formValues.dateRange = null;
          }

          return await listLog({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
    },
    treeConfig: {
      transform: false,
    },
  } as VxeTableGridOptions,
});

function onDelete() {
  const logIds = gridApi.grid.getCheckboxRecords().map((row) => row.logId);
  if (logIds && logIds.length > 0) {
    delLog(logIds).then(() => {
      gridApi.query();
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    });
  }
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <ElButton
          type="primary"
          @click="onDelete"
          v-access:code="['loginlog:remove']"
        >
          <Minus class="size-5" />
          {{ $t('ui.actionTitle.delete', [$t('common.log')]) }}
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
